# apps/exam_papers/serializers.py
from rest_framework import serializers
from django.core.validators import MinValueValidator, MaxValueValidator

from .models import ExamPaper
from apps.users.serializers import UserSimpleSerializer  # 假设有简化的用户序列化器
from apps.subjects.serializers import SubjectSerializer  # 假设有科目序列化器


class ExamPaperBaseSerializer(serializers.ModelSerializer):
    """
    试卷基础序列化器（供其他序列化器继承）
    包含通用字段定义
    """
    status_display = serializers.CharField(source='get_status_display', read_only=True, label="状态名称")

    class Meta:
        model = ExamPaper
        fields = [
            'id',
            'title',
            'description',
            'total_score',
            'duration_minutes',
            'difficulty',
            'creator',
            'subject',
            'status',
            'status_display',
            'generated_from',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class ExamPaperListSerializer(ExamPaperBaseSerializer):
    """
    试卷列表序列化器
    用于返回简要信息，减少数据量
    """
    creator = serializers.CharField(source='creator.username', read_only=True)
    subject = serializers.CharField(source='subject.name', read_only=True)

    class Meta(ExamPaperBaseSerializer.Meta):
        fields = [
            'id',
            'title',
            'total_score',
            'duration_minutes',
            'difficulty',
            'creator',
            'subject',
            'status',
            'status_display',
            'created_at',
            'updated_at',
        ]


class ExamPaperDetailSerializer(ExamPaperBaseSerializer):
    """
    试卷详情序列化器
    返回完整信息，包含关联对象的详细信息
    """
    creator = UserSimpleSerializer(read_only=True)  # 推荐：使用简化的用户序列化器
    subject = SubjectSerializer(read_only=True)     # 推荐：返回科目详情

    class Meta(ExamPaperBaseSerializer.Meta):
        fields = '__all__'


class ExamPaperCreateUpdateSerializer(serializers.ModelSerializer):
    """
    试卷创建/更新序列化器
    包含写操作的验证逻辑
    """

    class Meta:
        model = ExamPaper
        fields = [
            'id',  # ←← 添加这一行
            'title',
            'description',
            'total_score',
            'duration_minutes',
            'difficulty',
            'subject',
            'status',
            'generated_from',
            'creator',
            'tenant'
        ]
        read_only_fields = ['creator', 'id']  # ← 如果不设置值，会报错


        extra_kwargs = {
            'title': {
                'required': True,
                'error_messages': {'required': '试卷名称不能为空。'}
            },
            'subject': {
                'required': True,
                'error_messages': {'required': '必须选择一个科目。'}
            },
            'difficulty': {
                'validators': [MinValueValidator(1), MaxValueValidator(5)],
                'error_messages': {
                    'invalid': '难度必须是一个整数。',
                    'min_value': '难度不能小于1。',
                    'max_value': '难度不能大于5。'
                }
            }
        }

    def validate_difficulty(self, value):
        if not isinstance(value, int):
            raise serializers.ValidationError("难度必须为整数。")
        if value < 1 or value > 5:
            raise serializers.ValidationError("难度必须在1到5之间。")
        return value

    def validate_status(self, value):
        valid_statuses = dict(ExamPaper.STATUS_CHOICES).keys()
        if value not in valid_statuses:
            raise serializers.ValidationError(f"状态必须是以下之一：{', '.join(valid_statuses)}。")
        return value

    def create(self, validated_data):
        # 自动设置创建人
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['creator'] = request.user
        return super().create(validated_data)

    def update(self, instance, validated_data):
        # 可在此添加更新前的逻辑（如日志）
        return super().update(instance, validated_data)


class ExamPaperSerializer(ExamPaperBaseSerializer):
    """
    默认序列化器（可作为通用入口）
    根据场景动态选择，也可直接使用
    """
    pass